package com.example.emos.wx.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.emos.wx.entity.TbUser;
import com.example.emos.wx.exception.BusinessException;
import com.example.emos.wx.exception.EnumResultMsg;
import com.example.emos.wx.mapper.TbUserMapper;
import com.example.emos.wx.service.TbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cucumber.api.java.an.E;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author MC鹏浩
 * @since 2021-03-02
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    //appid
    @Value("${wx.appid}")
    private String appId;

    //微信请求密钥
    @Value("${wx.secret}")
    private String secret;

    /**
     * 获取openid
     * @param code
     */
    @Override
    public void getWxLogin(String code) {

        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.length() == 0) {
            throw new BusinessException(EnumResultMsg.WXAPPIDERRO.getCode(), EnumResultMsg.WXAPPIDERRO.getMsg());
        }

    }
}
